package cn.smbms.controller;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.smbms.pojo.Comments;
import cn.smbms.pojo.Hot;
import cn.smbms.pojo.Order;
import cn.smbms.pojo.Order_detail;
import cn.smbms.pojo.Product;
import cn.smbms.pojo.Trolley;
import cn.smbms.pojo.User;
import cn.smbms.pojo.User_address;
import cn.smbms.service.Order.OrderService;
import cn.smbms.service.comments.CommentsService;
import cn.smbms.service.hot.HotService;
import cn.smbms.service.order_detail.OrderDetailService;
import cn.smbms.service.product.ProductService;
import cn.smbms.service.trolley.TrolleyService;
import cn.smbms.service.user.UserService;
import cn.smbms.tools.Constants;
import cn.smbms.tools.KdniaoTrackQueryAPI;

import com.alibaba.fastjson.JSON;

@Controller
@RequestMapping(value = "/product")
public class ProductController {
	@Resource
	private ProductService productService;
	@Resource
	private TrolleyService trolleyService;
	@Resource
	private OrderService orderService;
	@Resource
	private UserService userService;
	@Resource
	private OrderDetailService orderDetailService;
	@Resource
	private HotService hotService;
	@Resource
	private CommentsService commentsService;

	// 显示商品信息
	@RequestMapping(value = "/detail/{id}")
	public String getDetail(HttpSession session, @PathVariable String id,
			Model model) {
		Product product = productService.getProductid(Integer.parseInt(id));
		User user = (User) session.getAttribute(Constants.USER_SESSION);
		List<Comments> listComments = commentsService.getComments(Integer
				.parseInt(id));
		List<Product> listtype = productService.getProucutType(
				product.getTypeid(), product.getId());
		model.addAttribute("listtype", listtype);
		model.addAttribute("listComments", listComments);
		if (user != null) {
			List<Product> listProduct = userService.getProduct(user.getId());
			for (Product pro : listProduct) {
				if (product.getId() == pro.getId()) {
					model.addAttribute("shouis", "1");
				}
			}
		} else {
			model.addAttribute("shouis", "2");
		}
		model.addAttribute(product);
		return "detail";
	}

	// 进入 商品列表页面(++++++++++此处直接调用的是综合的方法，那个方法查询所有给后台用了)
	@RequestMapping(value = "/ription.html")
	public String productlist(HttpServletRequest request,
			@RequestParam(value = "nr", required = false) String nr, Model model) {

		String nrs = "";

		if (nr != null) {

			try {
				nrs = new String(nr.getBytes("ISO-8859-1"), "UTF-8");
			} catch (UnsupportedEncodingException e) { // TODO Auto-generated
														// catch block
				e.printStackTrace();
			}

		}
		int count = productService.getCount(nrs);
		request.setAttribute("cot", count);
		request.setAttribute("concatName", nrs);
		List<Product> proList = productService.getProductByZh(nrs, 0, 4);
		List<Hot> hotList = hotService.getList();
		model.addAttribute("hotList", hotList);
		model.addAttribute("proList", proList);
		return "product";
	}

	// 综合显示
	@RequestMapping("/zhProduct")
	@ResponseBody
	public Object getZongHe(Model model, @RequestParam String concatName,
			@RequestParam Integer one, @RequestParam Integer two,
			HttpServletRequest request) {

		String nrs = "";

		if (concatName != null) {

			try {
				nrs = new String(concatName.getBytes("ISO-8859-1"), "UTF-8");
			} catch (UnsupportedEncodingException e) { // TODO Auto-generated
														// catch block
				e.printStackTrace();
			}

		}
		int count = productService.getCount(nrs);
		request.setAttribute("cot", count);
		System.out.println(one + "=========================" + two);
		List<Product> zhList = productService.getProductByZh(nrs, one, two);
		List<Hot> hotList = hotService.getList();
		model.addAttribute("hotList", hotList);
		return JSON.toJSONString(zhList);
	}

	// 显示最新商品
	@RequestMapping("/newproduct")
	@ResponseBody
	public Object getNewProduct(Model model, @RequestParam String concatName,
			@RequestParam String one, @RequestParam String two,
			HttpServletRequest request) {
		String nrs = "";

		if (concatName != null) {

			try {
				nrs = new String(concatName.getBytes("ISO-8859-1"), "UTF-8");
			} catch (UnsupportedEncodingException e) { // TODO Auto-generated
														// catch block
				e.printStackTrace();
			}

		}
		int count = productService.getCount(nrs);
		request.setAttribute("cot", count);
		List<Product> newList = productService.getNewProduct(nrs,
				Integer.parseInt(one), Integer.parseInt(two));
		List<Hot> hotList = hotService.getList();
		model.addAttribute("hotList", hotList);
		return JSON.toJSONString(newList);
	}

	// 价格从高到低
	@RequestMapping("/height")
	@ResponseBody
	public Object getHeight(Model model, @RequestParam String concatName,
			@RequestParam Integer one, @RequestParam Integer two,
			HttpServletRequest request) {
		String nrs = "";

		if (concatName != null) {

			try {
				nrs = new String(concatName.getBytes("ISO-8859-1"), "UTF-8");
			} catch (UnsupportedEncodingException e) { // TODO Auto-generated
														// catch block
				e.printStackTrace();
			}

		}
		int count = productService.getCount(nrs);
		request.setAttribute("cot", count);
		List<Product> heightList = productService.getByHeight(nrs, one, two);
		List<Hot> hotList = hotService.getList();
		model.addAttribute("hotList", hotList);
		return JSON.toJSONString(heightList);
	}

	// 价格从低到高
	@RequestMapping("/low")
	@ResponseBody
	public Object getLow(Model model, @RequestParam String concatName,
			@RequestParam Integer one, @RequestParam Integer two,
			HttpServletRequest request) {
		String nrs = "";

		if (concatName != null) {

			try {
				nrs = new String(concatName.getBytes("ISO-8859-1"), "UTF-8");
			} catch (UnsupportedEncodingException e) { // TODO Auto-generated
														// catch block
				e.printStackTrace();
			}

		}
		int count = productService.getCount(nrs);
		request.setAttribute("cot", count);
		List<Product> lowList = productService.getByLow(nrs, one, two);
		List<Hot> hotList = hotService.getList();
		model.addAttribute("hotList", hotList);
		return JSON.toJSONString(lowList);
	}

	// 分类查看商品
	@RequestMapping("/serachById.html")
	public String getById(@RequestParam("typeid") Integer typeid, Model model) {
		List<Product> proList = productService.getimgsById(typeid);
		List<Hot> hotList = hotService.getList();
		model.addAttribute("hotList", hotList);
		model.addAttribute("proList", proList);
		return "product";
	}

	// 价格0-99
	@RequestMapping("/one")
	@ResponseBody
	public Object getOne(Model model, @RequestParam String concatName) {
		String nrs = "";

		if (concatName != null) {

			try {
				nrs = new String(concatName.getBytes("ISO-8859-1"), "UTF-8");
			} catch (UnsupportedEncodingException e) { // TODO Auto-generated
														// catch block
				e.printStackTrace();
			}

		}
		List<Product> oneList = productService.getOne(nrs);
		List<Hot> hotList = hotService.getList();
		model.addAttribute("hotList", hotList);
		return JSON.toJSONString(oneList);
	}

	// 价格100-499
	@RequestMapping("/two")
	@ResponseBody
	public Object getTwo(Model model, @RequestParam String concatName) {
		String nrs = "";
		if (concatName != null) {

			try {
				nrs = new String(concatName.getBytes("ISO-8859-1"), "UTF-8");
			} catch (UnsupportedEncodingException e) { // TODO Auto-generated
														// catch block
				e.printStackTrace();
			}

		}
		List<Product> twoList = productService.getTwo(nrs);
		List<Hot> hotList = hotService.getList();
		model.addAttribute("hotList", hotList);
		return JSON.toJSONString(twoList);
	}

	// 价格>500
	@RequestMapping("/three")
	@ResponseBody
	public Object getThree(Model model, @RequestParam String concatName) {
		String nrs = "";
		if (concatName != null) {

			try {
				nrs = new String(concatName.getBytes("ISO-8859-1"), "UTF-8");
			} catch (UnsupportedEncodingException e) { // TODO Auto-generated
														// catch block
				e.printStackTrace();
			}

		}
		List<Product> threeList = productService.getThree(nrs);
		List<Hot> hotList = hotService.getList();
		model.addAttribute("hotList", hotList);
		return JSON.toJSONString(threeList);
	}

	// 进入订单界面
	@RequestMapping(value = "/sys/buyshop.html")
	public String buyshop(@RequestParam(value = "oid[]") String[] oid,
			HttpSession session, Model model) {
		User user = (User) session.getAttribute(Constants.USER_SESSION);// 获取登录用户
		List<Trolley> listtro = new ArrayList<Trolley>();
		double sum = 0;
		for (int i = 0; i < oid.length; i++) {
			Trolley tro = trolleyService.getTrolleyid(Integer.parseInt(oid[i]
					.toString()));
			listtro.add(tro);
			sum = sum + tro.getCount();

		}
		User_address user_address = userService.getUser_addressis(user.getId());// 获取默认地址
		model.addAttribute("sum", sum);
		model.addAttribute("user_address", user_address);

		model.addAttribute("user", user);

		model.addAttribute("listtro", listtro);
		return "buy";
	}

	// 进入订单界面
	@RequestMapping(value = "/sys/buyid.html")
	public String buyid(@RequestParam Integer oid, HttpSession session,
			Model model) {
		User user = (User) session.getAttribute(Constants.USER_SESSION);// 获取登录用户
		Order_detail orederdet = orderDetailService.getOrder_detailcu(oid);
		User_address user_address = userService.getUser_addressis(user.getId());// 获取默认地址

		Product product = productService.getProductid(orederdet.getProductId());
		model.addAttribute("user_address", user_address);
		model.addAttribute("sum", orederdet.getCost());
		model.addAttribute("user", user);
		model.addAttribute("number", orederdet.getQuantity());
		model.addAttribute("product", product);
		model.addAttribute("color", orederdet.getColor());
		model.addAttribute("size", orederdet.getSize());
		return "buy";
	}

	// 进入订单界面
	@RequestMapping(value = "/sys/buy.html")
	public String buy(@RequestParam Integer number, @RequestParam String color,
			@RequestParam String size, @RequestParam String proid,
			HttpSession session, Model model) {
		User user = (User) session.getAttribute(Constants.USER_SESSION);// 获取登录用户

		String colo = "";
		String dest = "";
		if (color != null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(color);
			colo = m.replaceAll("");
		}
		if (size != null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(size);
			dest = m.replaceAll("");
		}
		try {
			colo = new String(colo.getBytes("ISO-8859-1"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		User_address user_address = userService.getUser_addressis(user.getId());// 获取默认地址

		Product product = productService.getProductid(Integer.parseInt(proid));
		float sum = product.getPrice() * number;
		Order order = new Order();
		order.setUserId(user.getId());
		order.setCost(sum);
		if (user_address != null) {
			order.setUserAddress(user_address.getAddress());
			order.setPhone(user_address.getiPhone());
		} else {
			order.setUserAddress("kong");
			order.setPhone("kong");
		}

		order.setLoginName(user.getLoginName());

		String x = "";
		for (int n = 0; n < 13; n++) {
			x += (int) (10 * (Math.random()));
		}

		order.setSerialNumber(x);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式

		order.setCreateTime(df.format(new Date()));
		int i = orderService.add(order);
		if (i > 0) {
			int maxid = orderService.maxid();
			Order_detail orderdet = new Order_detail();
			orderdet.setSize(dest);
			orderdet.setColor(colo);
			orderdet.setOrderId(maxid);
			orderdet.setFahuoid(2);
			orderdet.setQuantity(number);
			orderdet.setProductId(product.getId());
			orderdet.setUserid(user.getId());
			orderdet.setZhifu(2);
			orderdet.setCost(sum);
			orderDetailService.addorderDetail(orderdet);
		}
		model.addAttribute("user_address", user_address);
		model.addAttribute("sum", sum);
		model.addAttribute("user", user);
		model.addAttribute("number", number);
		model.addAttribute("product", product);
		model.addAttribute("color", colo);
		model.addAttribute("size", dest);
		return "buy";
	}

	// 获取物流接口
	@RequestMapping(value = "/sys/LogisticCode", method = RequestMethod.POST)
	@ResponseBody
	public Object wuli(@RequestParam String traces) {
		KdniaoTrackQueryAPI api = new KdniaoTrackQueryAPI();
		String cresu = "";
		try {
			cresu = api.getOrderTracesByJson("YD", traces);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return cresu;
	}
}
